package com.yzcrm.erp.kms.service;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.yzcrm.erp.admin.service.AdminDeptService;
import com.yzcrm.erp.admin.service.AdminRoleService;
import com.yzcrm.erp.admin.service.AdminUserService;
import com.yzcrm.utils.FileUploadUtil;
import com.yzcrm.utils.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author jiang.xue
 */
public class KmsReportService {

    @Inject
    private AdminUserService adminUserService;

    @Inject
    private AdminDeptService deptService;

    @Inject
    private AdminRoleService adminRoleService;

    @Inject KmsCourseService courseService;

    /**
     * 知识库学习报表
     */
    public R report(String userName, String deptName, String courseName, Integer page, Integer limit) {

//        Kv kv = new Kv();
//        kv.set("userName", userName);
//        kv.set("deptName", deptName);
//        kv.set("courseName", courseName);
        if(ObjectUtil.isNotNull(page) && ObjectUtil.isNotNull(limit)) {
            page = (page-1)*limit;
        }
//        kv.set("page", page);
//        kv.set("limit", limit);

        // 检索部门
        List<Integer> listDeptId = new ArrayList<>();
        List<Record> listDeptRecord = deptService.queryDeptByName(deptName);
        listDeptRecord.forEach(record -> {

            Integer deptId = record.getInt("id");
            listDeptId.add(deptId);
        });

        if(ObjectUtil.isNotEmpty(deptName) && listDeptId.size() == 0) {
            return R.error("检索结果为空");
        }


        // 检索所有用户
        R r = adminUserService.queryAllUserList(userName, listDeptId, page, limit);
        List<Record> listRecord = (List<Record>) r.get("data");
        listRecord.forEach(record -> {

            Long userId = record.getLong("user_id");
            List<Integer> listUserRoles = adminRoleService.queryRoleIdsByUserId(userId);

            // 检索用户课程
            R rCourse = courseService.getUserCourseList(null, null, listUserRoles, userId, courseName);
            Map<String, Object> mapCourseRecord = (Map<String, Object>)(rCourse.get("data"));
            record.set("courses", mapCourseRecord);

        });


        r = adminUserService.queryAllUserList(userName, listDeptId, null, null);
        List<Record> listRecordCount = (List<Record>) r.get("data");
        Integer count = listRecordCount.size();


        JSONObject resultJsonObject = new JSONObject();
        resultJsonObject.put("list", listRecord);
        resultJsonObject.put("totalRow", count);

        return R.ok().put("data", resultJsonObject);
    }
    /**
     * 知识库学习报表 表头信息
     * @return
     */
    public List<Record> queryReportListHead() {

        List<Record> listHead = new ArrayList<>();
        listHead.add(new Record().set("name","姓名").set("fieldName","realname"));
        listHead.add(new Record().set("name","部门").set("fieldName","deptName"));
        listHead.add(new Record().set("name","职位").set("fieldName","post"));
        listHead.add(new Record().set("name","课程").set("fieldName","title"));
        listHead.add(new Record().set("name","学时（分钟）").set("fieldName","standardStudySeconds"));
        listHead.add(new Record().set("name","学习时长（分钟）").set("fieldName","studiedSeconds"));
        listHead.add(new Record().set("name","总学时（分钟）").set("fieldName","courses"));
        listHead.add(new Record().set("name","总学习时长（分钟）").set("fieldName","allCourseStudiedSeconds"));

        return listHead;
    }

    /**
     * 课程内容学习进度
     */
    public R reportCourse(Long userId) {

        // 检索所有课程
        List<Integer> listUserRoles = adminRoleService.queryRoleIdsByUserId(userId);
        R rCourse = courseService.getUserCourseList(null, null, listUserRoles, userId, null);
        Map<String, Object> mapCourseRecord = (Map<String, Object>)(rCourse.get("data"));

        // 课程遍历
        List<Record> listRecordCourse = (List<Record>)mapCourseRecord.get("list");
        listRecordCourse.forEach(course->{

            Kv kv = new Kv();
            kv.set("userId", userId);
            kv.set("courseId", course.getStr("course_id"));

            // 检索资源
            SqlPara sqlPara = Db.getSqlPara("kms.course.queryUserCourseResourceList", kv);
            List<Record> listResource = Db.find(sqlPara);
            listResource.forEach(record->{

                Long resourceId = record.get("resource_id");

                kv.set("resourceId", resourceId);

                // 检索资源下的文件
                SqlPara sqlPara2 = Db.getSqlPara("kms.resource.queryUserResourceFileListByResourceId", kv);
                List<Record> listFile = Db.find(sqlPara2);
                listFile.forEach(file->{

                    String path = file.getStr("path");
                    String url = FileUploadUtil.getPreviewURL(path);
                    file.set("url", url);
                });
                record.set("files", listFile);

            });

            course.set("resources", listResource);
        });

        JSONObject resultJsonObject = new JSONObject();
        resultJsonObject.put("list", listRecordCourse);
        resultJsonObject.put("totalRow", listRecordCourse.size());
        return R.ok().put("data", resultJsonObject);

    }

}
